# 日志类的封装
import logging
import logging.handlers
import os

import json
import os.path
from bs4 import BeautifulSoup

from 金融自动化.config import DIR_PATH


def parser_html(response):
    html = response.json().get("description").get("form")

    bs = BeautifulSoup(html, "html.parser")
    # 通过标签名提取
    url = bs.form.get("action")
    # print(url)
    data = {}
    # 查找Input
    for input in bs.find_all("input"):
        # print(input)
        name = input.get("name")
        value = input.get("value")
        data[name] = value
    return url, data


def read_json(filename, key):
    path = DIR_PATH + os.sep + "data" + os.sep + filename
    print(path)
    with open(path, encoding="utf-8") as f:
        arr = []
        for data in json.load(f).get(key):
            # print(data.values())
            tmp = tuple(data.values())[1:]
            arr.append(tmp)
        return arr


class GetLog:
    # 单例模式 一个类只有一个实例对象
    @classmethod
    def getLog(cls):
        cls.log = None

        if cls.log == None:
            # 获取日志器
            cls.log = logging.getLogger()
            # 设置日志级别
            cls.log.setLevel(logging.INFO)
            # 获取处理器
            file_name = DIR_PATH + os.sep + "log" + os.sep + "p2p.log"
            # print(file_name)
            # 按照时间分割 保存到log文件
            tf = logging.handlers.TimedRotatingFileHandler(filename=file_name,
                                                           when='midnight',
                                                           interval=1,
                                                           backupCount=3,
                                                           encoding="utf-8")
            # 获取日志格式
            fmt = "%(asctime)s - %(levelname)s - [%(filename)s- %(funcName)s] %(lineno)d  : %(message)s"
            fm = logging.Formatter(fmt)
            # 将格式添加到处理器
            tf.setFormatter(fm)
            # 将处理器添加到日志器
            cls.log.addHandler(tf)
        return cls.log


# if __name__ == '__main__':
#     print(read_json("register_login.json", "img_code"))
#     GetLog().getLog().info("信息界别测试")
import pymysql


class DBUtils:
    host = "121.43.169.97"
    user = "root"
    port = 3306
    password = "Itcast_p2p_20191228"
    database = "czbk_member"
    # 添加类属性
    conn = None

    # 获取链接
    @classmethod
    def __getConn(cls):
        if cls.conn is None:
            cls.conn = pymysql.connect(host=cls.host, user=cls.user, password=cls.password, port=cls.port,
                                       database=cls.database, charset="utf8", autocommit=True)
        return cls.conn

    # 关闭链接
    @classmethod
    def __closeConn(cls):
        if cls.conn is not None:
            cls.conn.close()
            cls.conn = None

    # 查询一条
    @classmethod
    def select_one(cls, sql):
        cursor = None
        result = None
        try:
            cls.conn = cls.__getConn()
            cursor = cls.conn.cursor()  # 获取游标
            print(cursor)
            cursor.execute(sql)  # 执行sql
            result = cursor.fetchone()  # 提取结果集

        except Exception as e:
            print(e)
        finally:
            cursor.close()  # 关闭游标
            cls.__closeConn()  # 关闭连接
            print("最后执行")
            return result

    # 查询多条
    @classmethod
    def select_all(cls, sql):
        cursor = None
        result = None
        try:
            cls.conn = cls.__getConn()
            cursor = cls.conn.cursor()  # 获取游标
            cursor.rownumber = 0  # 将游标位置回退为0
            cursor.execute(sql)  # 执行sql
            result = cursor.fetchall()  # 提取结果集

        except Exception as e:
            print(e)
        finally:
            cursor.close()  # 关闭游标
            cls.__closeConn()  # 关闭连接
            return result

    # 增删改
    @classmethod
    def uid_db(cls, sql):
        cursor = None
        try:
            cls.conn = cls.__getConn()
            cursor = cls.conn.cursor()
            cursor.execute(sql)
            cls.conn.commit()  # 提交事务
            print(f"受影响的行数：{cls.conn.affected_rows()}")
        except Exception as e:
            print(e)
            cls.conn.rollback()  # 回滚事务
        finally:
            cursor.close()  # 关闭游标
            cls.__closeConn()  # 关闭连接


# 清除方法
def clear_data():
    sql1 = """delete i.* from mb_member_info i INNER JOIN mb_member m on i.member_id=m.id where m.phone in (
    "1399151967","1399151968","1399151969","1399151966") """
    DBUtils.uid_db(sql1)
    # conn_mysql(sql1)
    sql2 = """delete l.* from mb_member_login_log l INNER JOIN mb_member m on l.member_id=m.id where m.phone in (
    "1399151967","1399151968","1399151969","1399151966") """
    DBUtils.uid_db(sql2)
    sql3 = """
    delete from mb_member_register_log where phone in ("1399151967","1399151968","1399151969","1399151966")
    """
    DBUtils.uid_db(sql3)
    sql4 = """
    delete from mb_member where phone in ("1399151967","1399151968","1399151969","1399151966")
    """
    DBUtils.uid_db(sql4)


if __name__ == '__main__':
    sql = "select * from mb_member"
    res = DBUtils.select_one(sql)
    print(res)

    # res = DBUtils.select_one("select * from user")
    # res_all = DBUtils.select_all("select * from user")
    # DBUtils.uid_db("update user set username='大大怪1' where id =12 ")
    # print(res_all)
